/*
 *  MooseFlag.h
 *  April13
 *
 * 
 *	Class for holding the flag objects..
 *
 */

#ifndef MOOSEFLAG_H
#define MOOSEFLAG_H
//----

#include <Ogre/Ogre.h>

using namespace Ogre;


class MooseFlag {
private:

	AnimationState *mAnimationState;
	Vector3 position;			// position in world coord.
	SceneManager *sceneMgr;
	SceneNode *node;
	
	//static int flags;
	
public:
	// constructor - set's name and adds the mesh in correct scale into the scenemanager. --------------------------
	MooseFlag::MooseFlag(SceneManager *sceneMgr)
	{
		this->sceneMgr = sceneMgr;
		
		// Add a model, mesh
		Ogre::Entity* flagEnt = sceneMgr->createEntity( "flag1", "Plane01.mesh");
		node = sceneMgr->getRootSceneNode()->createChildSceneNode( "flag1node");
		node->pitch(Ogre::Degree(90));
		
		mAnimationState = flagEnt->getAnimationState("FLAG_ANIM");
		mAnimationState->setLoop(true);
		mAnimationState->setEnabled(true);
		
		//node->scale(Vector3(5));
		node->attachObject(flagEnt);
		srand((unsigned) time(NULL));
		
		updatePosition();
		
	}
	
	Vector3 MooseFlag::getPosition()
	{
		return position;
	}
	
	void MooseFlag::updatePosition()
	{
		
		this->position.x = Math::RangeRandom(100, 12000-100);
		this->position.y = 1000;
		this->position.z = Math::RangeRandom(100, 12000-100);
		this->node->setPosition(position);
		
		// Lite strålföljning för att positionerna  ut flaggan i nivå med terrängen
		RaySceneQuery *raySceneQuery = sceneMgr->createRayQuery(Ogre::Ray(node->getPosition(), Vector3::NEGATIVE_UNIT_Y));
		
		//Skapar strålen
		static Ogre::Ray flagRay;
		
		//Sätter origin och direction för strålarna
		flagRay.setOrigin(position);
		flagRay.setDirection(Vector3::NEGATIVE_UNIT_Y);
		
		//Skapar querys för strålar
		raySceneQuery->setRay(flagRay);
		
		//Skapar iteratorer för frågorna (följer strålen)
		Ogre::RaySceneQueryResult& qryResult = raySceneQuery->execute();
		Ogre::RaySceneQueryResult::iterator i = qryResult.begin();
		
		//Tar in resultaten från strålen
		if (i != qryResult.end() && i->worldFragment)
		{					
			node->setPosition(node->getPosition().x, 
							  i->worldFragment->singleIntersection.y + 136, 
							  node->getPosition().z);
		}
		
	}
	
	void MooseFlag::updateAnimation(Real timeSinceLastFrame)
	{
		mAnimationState->addTime(timeSinceLastFrame);
	}
	
};
#endif